import axios from 'axios'
import { getToken, removeToken } from './auth'
import { Message } from 'element-ui'
import router from '@/router'
const actionMapper = {
  get: 'view',
  post: 'add',
  put: 'update',
  delete: 'delete',
}
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000,
})

service.interceptors.request.use(
  (request) => {
    const currentUrl = request.url
    request.headers['token'] = getToken()
    if (
      currentUrl !== '/admin/users/login' &&
      currentUrl !== '/admin/users/info'
    ) {
      // request.headers['token'] = getToken()
      const method = request.method
      const action = actionMapper[method]
      // console.log(action)
      const right = router.currentRoute.meta
      // console.log(right)
      if (right.indexOf(action) === -1) {
        alert('没有权限')
        return Promise.reject(new Error('没有权限'))
      } else if (right.length === 0) {
        alert('没有权限')
        return Promise.reject(new Error('没有权限'))
      }
    }
    return request
  },
  (error) => {
    // 请求出现错误
    console.log(error) // 请求错误信息
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    const res = response.data
    const message = res.msg
    if (res.code !== 200) {
      // 提示错误消息
      Message({
        message,
        type: 'error',
        duration: 5 * 1000,
      })

      // 401: 当前用户未登录
      if (res.code === 401) {
        removeToken()
        // 刷新页面
        location.reload()
      } else if (res.code === 403) {
        // 403: 用户没有访问权限
        router.push({ path: '/403' })
      }
      return Promise.reject(new Error(message))
    } else {
      return res
    }
  },
  (error) => {
    console.log('err', error) // 打印错误消息用于 debug
    Message({
      message: error.msg || error.message,
      type: 'error',
      duration: 5 * 1000,
    })
    return Promise.reject(error)
  }
)

export default service
